package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"
	"house/models/mysql"
)

type HouseListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHouseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HouseListLogic {
	return &HouseListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HouseListLogic) HouseList(in *houserpc.HouseListRequest) (*houserpc.HouseListResponse, error) {
	// todo: add your logic here and delete this line
	var houses []mysql.House
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	tx := mysql.DB.Debug().Limit(int(in.Size)).Offset(int(offset)).Find(&houses)
	if in.PriceOrder == 2 {
		tx.Order("price desc")
	}
	if in.PriceOrder == 1 {
		tx.Order("price asc")
	}
	//cache.Rdb.Get(l.ctx, "houses", time.Minute*10)
	//
	//result, _ := cache.Rdb.Get(l.ctx, "HouseList").Result()
	//if result != "" {
	//	marshal, _ := json.Marshal(houses)
	//	cache.Rdb.Set(l.ctx,"HouseList",marshal,time.Minute*15)
	//}else{
	//	json.Unmarshal([]byte(result),&houses)
	//}
	var HouseList []*houserpc.HouseList
	for _, house := range houses {
		list := houserpc.HouseList{
			Title:     house.Title,
			HeadImage: house.HeadImage,
			UserId:    int64(house.UserId),
			Context:   house.Context,
			Price:     float32(house.Price),
			Address:   house.Address,
		}
		HouseList = append(HouseList, &list)
	}
	return &houserpc.HouseListResponse{
		List: HouseList,
	}, nil
}
